/*
 * @Author: wangjun haodreams@163.com
 * @Date: 2024-07-05 14:37:50
 * @LastEditors: wangjun haodreams@163.com
 * @LastEditTime: 2025-05-24 18:52:53
 * @FilePath: \golib\trendpng\trendpng.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package xpng

import (
	"fmt"

	"gitee.com/haodreams/golib/logs"
	"github.com/vicanso/go-charts/v2"
)

// 趋势数据
type TrendData struct {
	Y      []float64 //值
	X      []string  //时间
	Max    float64
	Min    float64
	Title  string
	Legend string
	Png    []byte
}

// 生成趋势数据
// func NewTrendData(vals []*opdb.Real, title, legend string) (t *TrendData) {
// 	n := len(vals)
// 	t = new(TrendData)
// 	t.Title = title
// 	t.Legend = legend
// 	t.Y = make([]float64, n)
// 	t.X = make([]string, n)
// 	t.Max = vals[0].Value
// 	t.Min = t.Max
// 	for i, val := range vals {
// 		t.Y[i] = val.Value
// 		t.X[i] = easy.FormatTime(val.Time, "01-02_15:04:05")
// 		if t.Max < val.Value {
// 			t.Max = val.Value
// 		}
// 		if t.Min > val.Value {
// 			t.Min = val.Value
// 		}
// 	}
// 	return t
// }

// 生成趋势
func CreateTrend(trend *TrendData) []byte {
	yDivideCount := 5 //y 轴分割线个数
	if trend.Max == trend.Min {
		yDivideCount = 2
		trend.Max++
		trend.Min--
	}

	//xopt:=
	p, err := charts.LineRender(
		[][]float64{
			trend.Y,
		},
		charts.TitleTextOptionFunc(trend.Title),
		charts.XAxisDataOptionFunc(trend.X, charts.FalseFlag()),
		charts.LegendLabelsOptionFunc([]string{
			trend.Legend,
		}), //, "480"
		charts.MarkPointOptionFunc(0, charts.SeriesMarkDataTypeMax, charts.SeriesMarkDataTypeMin),
		func(opt *charts.ChartOption) {
			//opt.XAxis.SplitNumber = 60
			opt.XAxis.FontSize = 9
			opt.YAxisOptions = []charts.YAxisOption{{Min: &trend.Min, Max: &trend.Max, FontSize: 9, DivideCount: yDivideCount}}
			opt.Legend.Padding = charts.Box{
				Top:    5,
				Bottom: 10,
			}
			opt.SymbolShow = charts.FalseFlag()
			opt.LineStrokeWidth = 1
			opt.ValueFormatter = func(f float64) string {
				return fmt.Sprintf("%.0f", f)
			}
		},
	)
	if err != nil {
		logs.Warn(trend.Title, err)
		return nil
	}
	data, err := p.Bytes()
	if err != nil {
		logs.Warn(trend.Title, err)
		return nil
	}
	return data
}
